package shopping.front;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import shopping.commons.BaseAction;
import shopping.management.ManagementConstants;
import shopping.management.ProductAction;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: mazhao
 * Date: 2010/11/13
 * Time: 22:14:37
 * To change this template use File | Settings | File Templates.
 */
public class ProductImageAction extends BaseAction {
      private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

     public InputStream getInputStream() throws Exception {

         String fullPath = getText(ProductAction.KEY_PRODUCT_IMAGE_DIR) + path;

         // if file exist show the specificed file.
         // else show default file.
         File targetFile = new File(fullPath);
         if(targetFile.isDirectory()) {
             log.debug("file is directory, then choose default file. the folder is " + fullPath);
             File[] files = targetFile.listFiles(new FileFilter(){

                public boolean accept(File pathname) {
                    String fileName = pathname.getName();
                    String fileexts = fileName.substring(fileName.indexOf("."));
                    return ManagementConstants.IMAGE_FILE_EXTS.contains(fileexts);
                }
            });

            log.debug("threre are " + files.length + " files in the folder");

            if(files.length > 0) {
                fullPath = files[0].getAbsolutePath();
                log.debug("choose default file " + fullPath);
            }
         }

         log.debug("file full path:" + fullPath);

         return new FileInputStream(fullPath);
    }

    @Action(
        value="/front/productimage",
        results ={
            @Result(name="success",
                //location ="/management/productlist",
                type="stream",
                params={"contentType", "image/jpeg",
                    "inputName", "inputStream",
                    "bufferSize", "4096",
                    "contentDisposition", "filename=\"product.jpg\""
                }
            )
        }
    )
    public String show() throws Exception {
        return SUCCESS;
    }

    // ==============================
    // Show image in front
    // ==============================
    
}
